import 'package:flutter/cupertino.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/profile/models/model_question_items.dart';
import 'package:flutter_09_game/pages/profile/models/model_security_question.dart';
import 'package:flutter_09_game/pages/profile/profile_trc_manager/profile_trc_manager_logic.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:get/get.dart';

class ProfileFindFundPasswordLogic extends BaseController {
  RxString newFundPassword = ''.obs;
  RxString newFundPasswordConfirm = ''.obs;
  TextEditingController answerController = TextEditingController();
  RxBool isFormValid = false.obs;
  Rx<ModelSecurityQuestion> securityQuestion = Rx(ModelSecurityQuestion());

  // answer

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getUserSecurityQuestion();
    everAll([newFundPassword, newFundPasswordConfirm], (val) {
      validateForm();
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  getUserSecurityQuestion() async {
    HttpResponse response = await HttpManager().get(API.getUserSecurityQuestion,
        fromJson: ModelSecurityQuestion.fromJson);
    if (response.isSuccess) {
      securityQuestion.value = response.data;
    }
  }

  /// 表单验证
  void validateForm() {
    final isValid = answerController.text.length > 1 &&
        newFundPassword.value.length == 6 &&
        newFundPasswordConfirm.value.length == 6;

    isFormValid.value = isValid;
  }

  postUserChangeFundPassword() async {
    HttpResponse response =
        await HttpManager().post(API.postUserFindFundPassword,
            params: {
              'answer': answerController.text,
              'new_fund_password': newFundPassword.value,
              'new_fund_password_confirm': newFundPasswordConfirm.value,
            },
            uiType: HttpUIType.loadingAndToast);
    if (response.isSuccess) {
      if (Get.isRegistered<ProfileTrcManagerLogic>()) {
        Get.until((routting) =>
            routting.settings.name == AppRoutes.profileSafetyCenterPage);
      } else {
        Get.back(result: true);
      }

      // Get.until((routting) => routting.settings.name == AppRoutes.profileSafetyCenterPage);
      //
      LoadingUtils.showToast(LocaleKeys.setSuccess.tr);
      // AppUserManager().refreshUserInfo();
    }
  }
}
